package com.sqsf.annotation;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;
//将切面类交由spring容器管理
@Component
//标识当前类是切面类 配置springAOP切面自动代理配置 实现自动配置
//等价于<aop:aspect ref="myAspect">
@Aspect
public class MyAspect {
    //切点表达式的抽取
    //任意书写简单方法 使用注解定义 方法名就是切点表达式的id
    @Pointcut("execution(* com.sqsf.annotation.*.*(..))")
    public void all() {}
    //当前类中的通知可以直接使用方法名()  all()
    //其他切面类中的通知如果想使用则必须通过类名.方法名() MyAspect.all()


    //通知注解
    //@通知类型(value="切点表达式") 如果只有value可以省略value字段

    //前置通知注解
    @Before("all()")
    // <aop:before method="before" pointcut="execution(* com.sqsf.annotation.*.*(..))"/>
    public void before(){
        System.out.println("前置通知");
    }

    //后置通知注解
    @After("MyAspect.all()")
    // <aop:after method="after" pointcut="execution(* com.sqsf.annotation.*.*(..))"/>
    public void after(){
        System.out.println("后置通知");
    }

    //环绕通知注解
    @Around("MyAspect.all()")
    // <aop:around method="around" pointcut="execution(* com.sqsf.annotation.*.*(..))"/>
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        System.out.println("环绕通知"+ Arrays.toString(args));
        Object proceed = joinPoint.proceed(args);
        System.out.println("环绕通知"+ proceed);
        return proceed;
    }
    //异常通知注解
    @AfterThrowing(value = "MyAspect.all()",throwing = "e")
    //aop:after-throwing method="afterThrowing" pointcut="execution(* com.sqsf.annotation.*.*(..))" throwing="e"/>
    public void afterThrowing(Exception e){
        System.out.println("异常通知");
    }

    //返回通知注解
    @AfterReturning(value = "all()",returning = "res")
    //<aop:after-returning method="afterReturning" pointcut="execution(* com.sqsf.annotation.*.*(..))" returning="res"/>
    public void afterReturning(Object res){
        System.out.println("返回通知"+res);
    }
}